package com.ftl.gateway.api.v2.common.manager;

import com.ftl.gateway.api.v2.common.utils.StringUtils;
import com.ftl.gateway.api.v2.filter.dto.AuthCheckDTO;
import com.ftl.gateway.api.v2.filter.dto.AuthCheckReturnDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

@Component
public class RestTemplateManager {

    @Value("${auth.uri}")
    private String authUrl;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.prefix}")
    private String prefix;

    @Autowired
    private RestTemplate restTemplate;

    public AuthCheckReturnDTO getFromAuth(ServerHttpRequest request) {
        UriComponents uriComponents = UriComponentsBuilder.fromUriString(authUrl).build().encode();
        String accessToken = request.getQueryParams().getFirst("accessToken");
        String authorization = request.getHeaders().getFirst(tokenHeader);
        if (StringUtils.isEmpty(authorization)) {
            authorization = accessToken;
        }
        URI uri = uriComponents.toUri();
        AuthCheckDTO body = new AuthCheckDTO();
        body.setMethod(request.getMethod().toString());
        body.setUrl(request.getPath().toString());
        body.setToken(authorization);
        body.setApiKey(request.getHeaders().getFirst("api-key"));
        body.setShareToken(request.getHeaders().getFirst("share-token"));
        body.setFilterClientIds(request.getQueryParams().get("filter[client][in][]"));
        HttpEntity<AuthCheckDTO> httpEntity = new HttpEntity<>(body);
        return restTemplate.postForObject(uri, httpEntity, AuthCheckReturnDTO.class);
    }
}
